package ui.app.com.utile;

import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

/**
 * 参考：https://blog.csdn.net/qq_39001834/article/details/77884829
 * Created by 郭敏 on 2018/7/19 0019.
 */

public class SerialPortUtil {
    private final String TAG = "SerialPortUtil";
    private static SerialPortUtil serialPortUtil;
    private SerialPort serialPort = null;
    private InputStream inputStream = null;
    private OutputStream outputStream = null;
    //true 读取串口数据
    private boolean isReadValue = false;


    public static SerialPortUtil getInstance() {
        if (serialPortUtil == null) {
            serialPortUtil = new SerialPortUtil();
        }
        return serialPortUtil;
    }

    /**
     * @param port     串口路径（所在位置，不同的开发板操作的串口路径是不同的
     *                 ttyS5,ttyS1,ttyS）
     * @param baudrate 波特率要设置成一致，不然收到的数据会乱码。
     *                 9600
     */
    public void openSrialPort(String port, int baudrate) {
        if (TextUtils.isEmpty(port) || baudrate == 0) {
            return;
        }
        String portPath = "/dev/" + port;
        Log.e(TAG, "打开串口:" + portPath + " baudrate:" + baudrate);
        try {
            if (isReadValue) {
                closeSerialPort();
                return;
            }
            serialPort = new SerialPort(new File(portPath), baudrate, 0);
            //获取打开的串口中的输入输出流，以便于串口数据的收发
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();
            //接收串口数据
            new ReadSerialPort().start();

        } catch (IOException e) {
            closeSerialPort();
            e.printStackTrace();
            Log.e(TAG, "打开失败:" + e.getMessage());
        }

    }

    /**
     * 读取串口数据
     */
    class ReadSerialPort implements Runnable {
        @Override
        public void run() {
            while (isReadValue) {
                if (inputStream == null) {
                    isReadValue = false;
                    return;
                }
                BufferedReader readerValue = new BufferedReader(new InputStreamReader(inputStream));
                try {
                    String str;
                    while ((str = readerValue.readLine()) != null) {
                        if (TextUtils.isEmpty(str)) {
                            continue;
                        }
                        Log.e(TAG, "接收串口数据:" + str);
                        acceptAndNotify(str);
                    }
                    readerValue.close();

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }

        public void start() {
            if (isReadValue) {
                return;
            }
            isReadValue = true;
            new Thread(this).start();
        }
    }


    /**
     * @param value 接收到的内容
     */

    private void acceptAndNotify(String value) {
        Log.e("接收到指令", "----------value:" + value);
    }

    /**
     * 发送串口数据
     *
     * @paramdata data 要发送的数据
     */
    public void sendSerialPort(String data) {
        Log.e(TAG, "发送串口数据：" + data);
        try {
            byte[] sendData = data.getBytes();
            outputStream.write(sendData);
            outputStream.flush();
            Log.e(TAG, "发送串口数据成功！");
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "发送串口数据失败！");
        }

    }


    /**
     * 关闭串口
     */
    public void closeSerialPort() {

        Log.e(TAG, "关闭串口");

        try {
            if (serialPort != null) {
                serialPort.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            isReadValue = false;
            Log.e("关闭串口", "关闭完成");
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("关闭串口", "关闭失败");
        }
    }

}

